﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace AutomationTools.Procedimentos.SimulacaoUso.Aplicativo
{
    public class ExecutarBatch : IProcedimento
    {
        protected string fileName;
        protected ExecutarBatch() { }

        public ExecutarBatch(string fileName)
        {
            this.fileName = fileName;
        }

        public virtual object Executar(IContexto contexto)
        {
            ProcessStartInfo ProcessInfo;
            Process process;

            ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + fileName);
            ProcessInfo.CreateNoWindow = true;
            ProcessInfo.UseShellExecute = false;

            ProcessInfo.StandardOutputEncoding = Encoding.GetEncoding("Cp850");
            ProcessInfo.StandardErrorEncoding = Encoding.GetEncoding("Cp850");
            ProcessInfo.RedirectStandardError = true;
            ProcessInfo.RedirectStandardOutput = true;

            process = Process.Start(ProcessInfo);
            process.WaitForExit();

            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            

            dynamic din = contexto;
            din.BatchError = !String.IsNullOrEmpty(error);
            din.BatchErrorMessage = error;
            din.BatchExitCode = process.ExitCode;
            process.Close();
            return output;
        }

        public void ValidarEntrada(IContexto contexto)
        {
            throw new NotImplementedException();
        }
    }
}
